import { UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, Select, Upload, message } from 'antd';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import React, { Component, Fragment, useState } from 'react';
import { updateRule, queryCurrent } from '../service';
import * as RequestHelper from '@/helpers/RequestHelper';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import PreviewForm from "@/components/PreviewForm";

import { FormComponentProps } from '@ant-design/compatible/es/form';
import { connect } from 'dva';
import { CurrentUser } from '../data.d';
import GeographicView from './GeographicView';
import PhoneView from './PhoneView';
import styles from './BaseView.less';
import customerSettings from '../../../../../config/customSettings';

const FormItem = Form.Item;
const { Option } = Select;

// 初始化变量
const token = BdHelper.getBdToken()


// 设置上传文件值
var imgfileList = [];
const setUploadFile = (fileList: any) => {
  // const [picture, setPicture] = useState<any[]>([]);
  // setUploadChanged(true)
  const fileArr = DataHelper.getLastUploadFile(fileList)
  imgfileList = fileArr
  console.log("fileArr is ", fileArr)
  // return fileArr
}


// 头像组件 方便以后独立，增加裁剪之类的功能
// const AvatarView = ({ avatar }: { avatar: string }) => (
//   <Fragment>
//     <div className={styles.avatar_title}>
//       <FormattedMessage id="accountandsettings.basic.avatar" defaultMessage="Avatar" />
//     </div>
//     <div className={styles.avatar}>
//       <img src={imgfileList[0] ? imgfileList[0].file_url : avatar} alt="avatar" />
//     </div>
//     <Upload showUploadList={false}
//       action="/api/admin/file/upload"
//       listType="picture"
//       onChange={(changeObj) => setUploadFile(changeObj.fileList)}
//       headers={{
//         Authorization: `Bearer ${token}`,
//       }}
//       data={{ type: 'image' }}
//     // defaultFileList={defaultPicture}
//     >
//       <div className={styles.button_view}>
//         <Button>
//           <UploadOutlined />
//           <FormattedMessage
//             id="accountandsettings.basic.change-avatar"
//             defaultMessage="Change avatar"
//           />
//         </Button>
//       </div>
//     </Upload>
//   </Fragment>
// );
interface SelectItem {
  label: string;
  key: string;
}

const validatorGeographic = (
  _: any,
  value: {
    province: SelectItem;
    city: SelectItem;
  },
  callback: (message?: string) => void,
) => {
  const { province, city } = value;
  if (!province.key) {
    callback('Please input your province!');
  }
  if (!city.key) {
    callback('Please input your city!');
  }
  callback();
};

const validatorPhone = (rule: any, value: string, callback: (message?: string) => void) => {
  const values = value.split('-');
  if (!values[0]) {
    callback('Please input your area code!');
  }
  if (!values[1]) {
    callback('Please input your phone number!');
  }
  callback();
};

interface BaseViewProps extends FormComponentProps {
  currentUser?: CurrentUser;
}

//更新
const handleUpdate = async (fields: any) => {
  return RequestHelper.bdExec({
    fn: updateRule,
    args: fields,
    successMsg: formatMessage({ id: 'app.base.update-success' }),
    failMsg: formatMessage({ id: 'app.base.api-exception' }),
  });
};

class BaseView extends Component<BaseViewProps> {
  view: HTMLDivElement | undefined = undefined;

  state = {
    fileList: [],
    fileId: 0,
    file_url: '',
    file_id: '',
    avatar: '/images/avatar.png'
  }

  componentDidMount() {
    this.setBaseInfo();
  }

  setBaseInfo = () => {
    const { currentUser, form } = this.props;
    if (currentUser) {
      Object.keys(form.getFieldsValue()).forEach(key => {
        const obj = {};
        obj[key] = currentUser[key] || null;
        form.setFieldsValue(obj);
      });
    }
    this.setState({
      avatar: this.getAvatarURL()
    });
  };

  getAvatarURL() {
    const { currentUser } = this.props;
    console.log('currentUser', currentUser)
    if (currentUser) {
      if (currentUser.avatar) {
        return currentUser.avatar;
      }
      const url = '/images/avatar.png';
      return url
    }
    return '';
  }

  getViewDom = (ref: HTMLDivElement) => {
    this.view = ref;
  };

  uploadChangeOnAvatar = (changeObj: any) => {
    console.log(changeObj)
    console.log("status ", changeObj.file.status)

    if (changeObj.file.status === 'done') {
      const fileInfo = changeObj.fileList[0].response;

      if (fileInfo.code == 0) {
        this.setState({
          avatar: fileInfo.data.file_url,
          file_url: fileInfo.data.file_url,
          file_id: fileInfo.data.file_id,
        })
      }

    }

    const fileList = changeObj.fileList
    if (fileList.length > 0) {
      const file = fileList[fileList.length - 1]
      this.setState({
        fileList: [file],
      })
    } else {
      this.setState({
        fileList: changeObj.fileList,
      })
    }

  }

  handlerSubmit = (event: React.MouseEvent) => {
    event.preventDefault();
    const { form } = this.props;
    const { currentUser } = this.props;
    const { fileList } = this.state
    console.log('prop', this.props);
    // const fileArr = setUploadFile(fileList: any)
    form.validateFields((err, fieldsValue) => {
      if (fileList.length > 0) {
        fieldsValue.file_id = this.state.file_id
        fieldsValue.file_url = this.state.file_url
      }
      fieldsValue.id = currentUser.userid;
      // debugger
      handleUpdate(fieldsValue).then((success: any) => {
        console.log('handleSubmit then success is ', success)
        if (success) {
          // form.resetFields()
          queryCurrent()
        }
      })
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { currentUser } = this.props;
    const { avatar, fileList } = this.state
    return (
      <div className={styles.baseView} ref={this.getViewDom}>
        <div className={styles.left}>
          <Form layout="vertical" hideRequiredMark>
            <FormItem label={formatMessage({ id: 'accountandsettings.basic.email' })}>
              {getFieldDecorator('email', {
                // initialValue: currentUser.email,
                rules: [
                  {
                    required: false,
                    message: formatMessage({ id: 'accountandsettings.basic.email-message' }, {}),
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label={formatMessage({ id: 'accountandsettings.basic.nickname' })}>
              {getFieldDecorator('nickname', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'accountandsettings.basic.nickname-message' }, {}),
                  },
                ],
              })(<Input disabled={true} />)}
            </FormItem>
            {
              customerSettings.appName == 'crm' && (
                <FormItem label={'分机号'}>
                  {getFieldDecorator('sub_tel_code', {
                    rules: [
                      {
                        required: false,
                        message: formatMessage({ id: 'accountandsettings.basic.nickname-message' }, {}),
                      },
                    ],
                  })(<Input />)}
                </FormItem>
              )
            }
            <FormItem label={formatMessage({ id: 'accountandsettings.basic.profile' })}>
              {getFieldDecorator('remark', {
                // initialValue: currentUser.remark,
                rules: [
                  {
                    required: false,
                    message: formatMessage({ id: 'accountandsettings.basic.profile-message' }, {}),
                  },
                ],
              })(
                <Input.TextArea
                  placeholder={formatMessage({
                    id: 'accountandsettings.basic.profile-placeholder',
                  })}
                  rows={4}
                />,
              )}
            </FormItem>
            {/* <FormItem label={formatMessage({ id: 'accountandsettings.basic.country' })}>
              {getFieldDecorator('country', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'accountandsettings.basic.country-message' }, {}),
                  },
                ],
              })(
                <Select style={{ maxWidth: 220 }}>
                  <Option value="China">中国</Option>
                </Select>,
              )}
            </FormItem> */}
            {/* <FormItem label={formatMessage({ id: 'accountandsettings.basic.geographic' })}>
              {getFieldDecorator('geographic', {
                rules: [
                  {
                    required: true,
                    message: formatMessage(
                      { id: 'accountandsettings.basic.geographic-message' },
                      {},
                    ),
                  },
                  {
                    validator: validatorGeographic,
                  },
                ],
              })(<GeographicView />)}
            </FormItem> */}
            {/* <FormItem label={formatMessage({ id: 'accountandsettings.basic.address' })}>
              {getFieldDecorator('address', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'accountandsettings.basic.address-message' }, {}),
                  },
                ],
              })(<Input />)}
            </FormItem> */}
            {/* <FormItem label={formatMessage({ id: 'accountandsettings.basic.phone' })}>
              {getFieldDecorator('phone', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'accountandsettings.basic.phone-message' }, {}),
                  },
                  { validator: validatorPhone },
                ],
              })(<PhoneView />)}
            </FormItem> */}
            <Button type="primary" onClick={this.handlerSubmit}>
              <FormattedMessage
                id="accountandsettings.basic.update"
                defaultMessage="Update Information"
              />
            </Button>
          </Form>
        </div>
        <div className={styles.right}>
          {/* <AvatarView avatar={this.getAvatarURL()} />
         */}
          <Fragment>
            <div className={styles.avatar}>
              <img src={avatar} alt="avatar" />
            </div>
            <Upload fileList={fileList}
              action="/api/admin/file/upload"
              headers={{
                // bdToken: bd_token,
                Authorization: `Bearer ${token}`,
                // TokenType: tokenType,
              }}
              data={{ type: 'image' }}
              onChange={(changeObj) => this.uploadChangeOnAvatar(changeObj)}>
              <div className={styles.button_view}>
                <Button icon="upload">
                  <FormattedMessage id="app.settings.basic.avatar" defaultMessage="Change avatar" />
                </Button>
              </div>
            </Upload>
          </Fragment>
        </div>
      </div>
    );
  }
}

export default connect(
  ({ accountAndsettings }: { accountAndsettings: { currentUser: CurrentUser } }) => ({
    currentUser: accountAndsettings.currentUser,
  }),
)(Form.create<BaseViewProps>()(BaseView));
